import { mapGetters } from 'vuex'

export default {
  computed: {
    ...mapGetters(['visitedViews'])
  },
  methods: {
    /**
     * 函数功能简述
     * @date     2018-11-21
     * @param    {Object}  oldRouterView     旧的路由对象 真实的路由对象{ path:'',fullpath:'';}
     * @param    {Object}  newRouterView     新的路由对象 { path:'';} { name:'';}
     */
    // 关闭旧路由跳转路由(没有会添加，有会刷新)
    jumpRouterView(oldRouterView, newRouterView) {
      // 关闭旧的路由
      this.$store
        .dispatch('delView', oldRouterView)
        .then(({ visitedViews }) => {
          const newRouterViewArr = visitedViews.filter(view => {
            return (
              view.path === newRouterView.path ||
              view.name === newRouterView.name
            )
          })
          if (newRouterViewArr.length > 0) {
            console.log(Object.assign({}, newRouterViewArr[0], newRouterView))
            // 合并参数
            this.refreshRouterView(
              Object.assign({}, newRouterViewArr[0], newRouterView)
            )
          } else {
            this.$router.push(newRouterView)
          }
        })
    },
    // 刷新路由
    refreshRouterView(view) {
      this.$store.dispatch('delCachedView', view).then(() => {
        // const { fullPath, query } = view
        this.$nextTick(() => {
          this.$router.replace(view)
        })
      })
    },
    // 关闭旧路由，跳转新路由(如果有这个路由不刷新新路由)
    // 跳转缓存路由
    jumpRouterCachedView(oldRouterView, newRouterView) {
      this.$store.dispatch('delView', oldRouterView)
      this.$router.push(newRouterView)
    },
    // 关闭
    closeView(view) {
      this.$store.dispatch('delView', view).then(({ visitedViews }) => {
        if (this.isActiveView(view)) {
          const latestView = visitedViews.slice(-1)[0]
          // console.log(latestView)
          if (latestView) {
            this.$router.push(latestView)
          } else {
            this.$router.push('/')
          }
        }
      })
    },
    isActiveView(route) {
      return route.path === this.$route.path
    },
    // 跳转页面
    goRouterView(url) {
      this.$router.push(url)
    },
    // 关闭当前路由,返回到页面
    backRouterView(url) {
      this.jumpRouterCachedView(this.$route, url)
    }
  }
}
